import java.awt.Dimension;
import java.util.Arrays;

import javax.swing.*;


@SuppressWarnings("serial")
public class GamePanel extends JSplitPane
{
	JTabbedPane gameTabs;
	ChatPanel chat;

	public GamePanel(JScrollPane pane, ChatPanel panel) 
	{
		super(JSplitPane.HORIZONTAL_SPLIT, null, pane);
		pane.setMinimumSize(new Dimension(300,0));
		setBorder(null);
		setDividerSize(0);
		setDividerLocation(0.0F);

		gameTabs = new JTabbedPane();
		setLeftComponent(gameTabs);
		
		chat = panel;
	}

	public void playerMoved(int id, String user, char[] board)
	{
		for(int i = 0; i < gameTabs.getTabCount(); i++)
		{
			Game tab = (Game)gameTabs.getComponentAt(i);
			if(tab.getID()==id)
			{
				tab.refresh(board);
				tab.playerTurn();
				return;
			}
		}
		
		
		Game tab = createGame(7, user);
		tab.setID(id);
		if(board != null)
		{
			if(board.length == 2)
			{
				System.out.println("--" + board[0] + "--");
				((TicTacToePanel)tab).isTurn = true;
				((TicTacToePanel)tab).playerType = 1;
			}
			else
				tab.refresh(board);
		}
		gameTabs.addTab(user, (JComponent)tab);
		gameTabs.setTabComponentAt(gameTabs.getTabCount()-1, new ButtonTabComponent(gameTabs, this));

		setDividerSize(5);
		setDividerLocation(200);
	}

	public void startGame(String username) 
	{
		System.out.println(username);
		this.sendData(7, username, "START");
	}

	public char[] connectGame(int id, String username) 
	{
		char[] array = new char[2];
		for(int i = 0; i < array.length; i++) { 
			array[i] = ' ';
		}
		System.out.println(id);
		System.out.println(username);
		this.sendData(id, username, array);
		return array;
	}
	
	public void endGame(int id, String username)
	{
		(new Talker(id, username, "NONE", chat.getIP(username))).start();
		endGame(id);
	}
	
	public void endGame(int id)
	{
		gameTabs.remove(getGame(id));
		if(gameTabs.getTabCount() == 0)
		{
			setDividerSize(0);
			setDividerLocation(0.0F);
		}
	}
	
	public int getGame(int id)
	{
		for(int i = 0; i < gameTabs.getTabCount(); i++)
		{
			Game tab = (Game)gameTabs.getComponentAt(i);
			if(tab.getID() == id)
				return i;
		}
		return -1;
	}
	
	public void sendData(int id, String username, char[] arr)
	{
		sendData(id,username,Arrays.toString(arr));
	}
	
	public void sendData(int id, String username, String msg)
	{
		(new Talker(id, chat.username, msg, chat.getIP(username))).start();
	}

	private Game createGame(int id, String user) 
	{
		switch(id)
		{
		case 7:
			return new TicTacToePanel(id, user, this);
		}
		return null;
	}
}
